const fileUpload = require('express-fileupload')
const bodyParser = require('body-parser')
const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const _ = require('lodash')
const contentType = require('content-type')
const app = express()
const getRawBody = require('raw-body')

const mongoose = require('mongoose')
const connect = require('./db/mongoose.js')
const db = connect()
// enable files upload
app.use(
  fileUpload({
    createParentPath: true,
    limits: {
      fileSize: 2 * 1024 * 1024 * 1024, //2MB max file(s) size
    },
  })
)

function getRawBodyFun(req, res, next) {
  getRawBody(
    req,
    {
      length: req.headers['content-length'],
      limit: '1mb',
      encoding: contentType.parse(req).parameters.charset,
    },
    function (err, string) {
      if (err) return next(err)
      req.text = string
      next()
    }
  )
}
function ignoreRoute(regexp, middleware, middleware2) {
  return function (req, res, next) {
    if (regexp.test(req.url) && req.method === 'DELETE') {
      return middleware(req, res, next)
    } else {
      return middleware2(req, res, next)
    }
  }
}
//add other middleware
var corsOptions = {
  origin: 'http://nft.thegamefi.io',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions))
app.use(ignoreRoute(/^\/upload/, getRawBodyFun, bodyParser.json()))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(morgan('dev'))

app.use(express.static('uploads'))

const styleRouter = require('./routes/style')
const uploadRouter = require('./routes/upload')
const taskRouter = require('./routes/task')

app.use('/upload', uploadRouter)
app.use('/style', styleRouter)
app.use('/task', taskRouter)

// 注册
app.post('/signup', async (req, res) => {
  const User = mongoose.model('User')
  const user = await User.findOne({ name: req.body.name })
  if (user) {
    res.send({
      status: false,
      message: `用户名 ${req.body.name} 已存在`,
    })
  } else {
    try {
      await User.create(req.body)
      res.send({
        status: true,
        message: 'ok',
      })
    } catch (e) {
      console.log(e)
      res.send({
        status: false,
        message: e.toString(),
      })
    }
  }
})
// 登录
app.post('/signin', async (req, res) => {
  const User = mongoose.model('User')
  const user = await User.findOne({ name: req.body.name || "" , password: req.body.password || ""})
  
  const data = {}
  if (user) {
    data.id = user._id
    data.name = user.name
    data.avatar = user.avatar
    data.like = user.like
  }

  res.send({
    status: !!user,
    message: !!user ? 'ok' : '账号或密码错误',
    data,
  })
})

//start app
const port = process.env.PORT || 3000

app.listen(port, () => console.log(`App is listening on port ${port}.`))
